<template>
  <div class="container">
    <partitionTree dialogName="分类" :nodeData="CustomerList" :classList="mapping" :deepseek="1" FileName="xxx"
      :addTemplate="true" :defaultProps="defaultProps" :defaultExpandAll="true" @handleNodeClick="handleNodeClick"
      ref="partitionTree" @toggleVisibility="toggleVisibility" @addDepartment="getData">
    </partitionTree>
    <div class="right">
      <!-- <connsearch
        ref="connsearch"
        :formOptions="formOptions"
        @search="search"
        @reset="reset"
    /> -->
      <el-button type="primary" @click="handleAdd">{{ materialType }}</el-button>

      <el-table class="materialTable" v-if="type === 'local'" stripe :data="localData">
        <el-table-column label="序号" width="60" type="index" :index="(index) => {
          return index + 1 + (this.pageNum - 1) * this.pageSize;
        }
          ">
        </el-table-column>
        <el-table-column prop="Class" label="分类" width="150" show-overflow-tooltip />
        <el-table-column prop="Name" label="素材名称" show-overflow-tooltip />
        <el-table-column prop="Files" label="文件名" width="300" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{row.Files.map(item => item.FileRawName).join(', ')}}
          </template>
        </el-table-column>
        <el-table-column prop="Descp" label="描述" show-overflow-tooltip />
        <el-table-column prop="Status" label="素材状态" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span :style="{ color: row.Status === 2 ? '#67C23A' : '#F56C6C' }">{{
              row.Status === 1 ? "未创建训练任务" : "已创建训练任务"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="CreateTime" label="创建时间" width="150" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span>{{ parseTime(row.CreateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150px">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="delLocal(scope.row)">删除</el-button>
            <el-button type="success" size="mini" @click="handlePreview(scope.row)">预览</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-table class="materialTable" v-if="type === 'net'" stripe :data="netData">
        <el-table-column label="序号" width="60" type="index" :index="(index) => {
          return index + 1 + (this.pageNum - 1) * this.pageSize;
        }
          ">
        </el-table-column>
        <el-table-column prop="Class" label="分类" show-overflow-tooltip />
        <el-table-column prop="Name" label="素材名称" show-overflow-tooltip />
        <el-table-column prop="NetFileSerName" label="服务器" show-overflow-tooltip />
        <el-table-column prop="NetDirPath" label="目录" show-overflow-tooltip />
        <el-table-column prop="Descp" label="描述" show-overflow-tooltip />
        <el-table-column prop="IsTrackDel" label="跟踪删除">
          <template slot-scope="{ row }">
            <span :style="{ color: row.IsTrackDel === 1 ? '#67c23a' : '#f56c6c' }">{{
              row.IsTrackDel === 1 ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="IsTrackUpdate" label="跟踪更新">
          <template slot-scope="{ row }">
            <span :style="{ color: row.IsTrackUpdate === 1 ? '#67c23a' : '#f56c6c' }">{{
              row.IsTrackUpdate === 1 ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="素材状态" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span :style="{ color: statusConfig[row.Status] && statusConfig[row.Status].color }">
              {{ (statusConfig[row.Status] && statusConfig[row.Status].text) || "未知" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="CreateTime" label="创建时间" width="150" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span>{{ parseTime(row.CreateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="LastUpdateTime" label="状态更新时间" width="150" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span>{{ parseTime(row.LastUpdateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150px">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="delNet(scope.row)">删除</el-button>
            <el-button type="success" size="mini" @click="handlePreview(scope.row)">预览</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
        :page-size="pageSize" background layout="total, prev, pager, sizes, next, jumper" :total="total">
      </el-pagination>
    </div>

    <MaterialDialog :Action="Action" :type="type" :show="display" :classList="classList" :dialogForm="dialogForm"
      @closeDialog="closeDialog" @submitDialog="submitDialog" />
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { getNowDay, parseTime, getTreeData, ParamDictURLtype, Maintype } from "@/utils/index.js";
import { getKnowledge } from "@/api/material";
import { Material_URLS } from "../api/request.js";
import connsearch from "@/components/connSearch";
import partitionTree from "@/components/partitionTree";
import MaterialDialog from "./MaterialDialog.vue";
import { noTokenRequest } from "@/api/material";
import { connrequest, directRequest } from "@/api/firstPage";
export default {
  name: "KnowledgeMaterial",
  components: {
    partitionTree,
    MaterialDialog
  },
  computed: {
    materialType() {
      return this.type === "local" ? "本地素材" : "网络素材";
    }
  },
  props: {
    type: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      display: false,
      color: "",
      dialogForm: {},
      statusConfig: {
        1: { text: "等待", color: "#909399" },
        2: { text: "运行", color: "#67c23a" },
        3: { text: "停止", color: "#ccc" },
        4: { text: "异常", color: "#f56c6c" }
      },
      formOptions: [
        {
          col: 10,
          label: "更新时间",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: "",
          events: {
            input(val) {
              that.searchform.timeRange = val;
            }
          }
        },
        {
          col: 8,
          label: "素材名称",
          prop: "Descp",
          element: "el-input",
          placeholder: "请输入素材名称",
          events: {
            input(val) {
              that.searchform.Descp = val;
            }
          }
        }
      ],
      CustomerList: [
        {
          Class: "所有知识库",
          children: []
        }
      ],
      defaultProps: {
        children: "children",
        label: "Class"
      },
      classList: [],
      mapping: [], //定义一个变量接收res.Data
      Files: [],
      localData: [],
      netData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchform: {},
      Action: 0,
      KnowledgeIP: "" //知识库的IP地址
    };
  },
  mounted() {
    this.color = localStorage.getItem("isNightMode") || "night";

    this.getKnowledgeIP().then(() => {
      if (this.checkHasIP()) {
        this.getData();
      } else {
        this.$message.error("请先配置知识库地址");
      }
      this.pageSize = Cookies.get("DefaultPageLength") * 1;
      let endTime = new Date(new Date().setHours(0, 0, 0, 0));
      let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
      let arr = [parseTime(startTime), ""];
      this.formOptions.map((item) => {
        if (item.label === "更新时间") {
          item.initValue = arr;
        }
      });
      this.$set(this.searchform, "timeRange", arr);
    });
  },
  methods: {
    parseTime,
    search(val) {
      this.pageNum = 1;
      this.searchform = { ...val };
      if (this.searchform.timeRange) {
        this.searchobj = {
          StartTime: this.searchform?.timeRange[0] || "",
          EndTime: this.searchform?.timeRange[1] || ""
        };
      }
    },
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0));
      let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
      let arr = [parseTime(startTime), ""];
      this.pageNum = 1;
      this.formOptions = this.formOptions.map((item) => {
        if (item.label === "更新时间") {
          item.initValue = arr;
        } else {
          item.initValue = "";
        }
        return item;
      });
      this.searchform = {};
      this.$set(this.searchform, "timeRange", arr);
      this.$refs.connsearch.addInitValue();
      this.getData();
    },
    toggleVisibility(isHidden) {
      if (isHidden) this.containerWidth = "100%";
      else this.containerWidth = "calc(100% - 240px)";
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.getMaterial();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.getMaterial();
    },
    checkHasIP() {
      this.KnowledgeIP = localStorage.getItem("KnowledgeIP");
      if (this.KnowledgeIP) {
        return true;
      } else {
        this.$message.error("请先配置知识库地址");
        return false;
      }
    },
    handleAdd() {
      if (this.checkHasIP()) {
        this.Action = 0;
        this.display = true;
      }
    },
    async submitDialog(submitData) {
      if (this.type === "local") {
        const res = await noTokenRequest(Material_URLS.addLocalMaterial, submitData);
        if (res.Status.StatusCode === 0) {
          this.$message.success("新增成功!");
          this.getMaterial();
          // 清空数据列表
          this.dialogForm = {};
          this.display = false; // 关闭对话框
        }
      } else {
        const res = await noTokenRequest(Material_URLS.addNetMaterial, { ...submitData, NetDirPath: `/${submitData.NetDirPath.join('/')}` });
        if (res.Status.StatusCode === 0) {
          this.$message.success("新增成功!");
          this.getMaterial();
          // 清空数据列表
          this.dialogForm = {};
          this.display = false; // 关闭对话框
        }
      }
    },
    closeDialog() {
      this.dialogForm = {};
      this.display = false;
    },
    async handleNodeClick({ data }) {
      this.pageNum = 1;
      if (this.type === "local") {
        await this.getMaterial({ ClassID: data.ID });
      } else {
        await this.getMaterial({ ClassID: data.ID });
      }
    },
    addClass(data) {
      return data.map((item) => {
        return {
          ...item,
          Class: this.getClassPathById(this.mapping, item.ClassID) || "未知分类"
        };
      });
    },
    getClassPathById(list, id) {
      // 转成 map，方便查找
      const map = {};
      list.forEach(item => {
        map[item.ID] = item;
      });

      // 递归获取路径
      function buildPath(node) {
        if (!node) return "";
        if (node.ParentID === 0) {
          return node.Class; // 根节点
        }
        const parent = map[node.ParentID];
        return buildPath(parent) + " / " + node.Class;
      }

      return buildPath(map[id]);
    },
    // 将树结构数据转换成级联选择器要展示的数据
    transformData(data) {
      return data.map((item) => ({
        value: item.ID,
        label: item.Class,

        children: item.children && item.children.length ? this.transformData(item.children) : null
      }));
    },
    // 将获取到的分类信息转化成树状结构
    buildTree(data) {
      const map = {};
      const roots = [];

      // 初始化每个节点的 Children 数组
      data.forEach((item) => {
        map[item.ID] = { ...item, children: [] };
      });

      // 构建树关系
      data.forEach((item) => {
        if (item.ParentID === 0) {
          roots.push(map[item.ID]);
        } else {
          if (map[item.ParentID]) {
            map[item.ParentID].children.push(map[item.ID]);
          }
        }
      });

      return roots;
    },
    async getKnowledgeMaterial() {
      const res = await noTokenRequest(Material_URLS.getClassify);
      if (res.Status.StatusCode === 0) {
        this.CustomerList[0].children = this.buildTree(res.Data);
        this.mapping = res.Data;
        this.classList = this.transformData(this.CustomerList[0].children);
      }
    },
    async getData() {
      await this.getKnowledgeMaterial();
      await this.getMaterial();
    },
    async getKnowledgeIP() {
      const res = await connrequest("GetKnowledgebaseConf");
      if (res.Status.StatusCode === 0) {
        this.knowledgeBase = { ...res.Data };
        localStorage.setItem("KnowledgeIP", res?.Data?.IP);
      }
    },
    async getMaterial(param) {
      const data = {
        ClassID: param?.ClassID || 0,
        Paging: {
          QueryPageNo: param?.Paging?.QueryPageNo || this.pageNum,
          QueryPageLength: param?.Paging?.QueryPageLength || this.pageSize
        }
      };
      if (this.type === "local") {
        const res = await noTokenRequest(Material_URLS.getLocalMaterial, data);
        if (res.Status.StatusCode === 0) {
          this.localData = res.Data ? this.addClass(res.Data) : [];
          this.total = res.Paging.TotalCount;
        }
      } else {
        const res = await noTokenRequest(Material_URLS.getNetMaterial, data);
        if (res.Status.StatusCode === 0) {
          this.netData = res.Data ? this.addClass(res.Data) : [];
          this.total = res.Paging.TotalCount;
        }
      }
    },
    async delNet(row) {
      await this.$msgbox.confirm("确定删除该网络素材吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });
      const data = { IDs: [row.ID] };
      const res = await noTokenRequest(Material_URLS.delNetMaterial, data);
      if (res.Status.StatusCode === 0) {
        this.$message.success("删除成功!");
        this.getMaterial();
      }
    },
    async delLocal(row) {
      await this.$msgbox.confirm("确定删除该本地素材吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });
      const data = { IDs: [row.ID] };
      const res = await noTokenRequest(Material_URLS.delLocalMaterial, data);
      if (res.Status.StatusCode === 0) {
        this.$message.success("删除成功!");
        this.getMaterial();
      }
    },
    handlePreview(row) {
      this.Action = 1;
      this.dialogForm = { ...row };
      this.display = true;
    },
    getClassFullPath(classItem) {
      let path = [];
      while (classItem.ParentID !== 0) {
        path.unshift(classItem);
        classItem = this.mapping.find((item) => item.ID === classItem.ParentID);
      }
      return path.map((item) => item.Class).join(" / ");
    },
    handleTableClass(classItem) {
      return this.getClassFullPath(this.mapping.find((item) => item.ID === classItem.ClassID));
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  margin-bottom: 15px;
}

::v-deep .el-upload-dragger,
::v-deep .el-upload.el-upload--text {
  width: 100%;
}

.right {
  position: relative;
  background-color: #fff;
  width: calc(100% - 260px);
  padding: 20px 20px 8px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-left: 10px;
}

.materialTable {
  margin-top: 15px;
}

::v-deep .el-tree {
  height: calc(100vh - 145px) !important;
}

::v-deep .el-tree-wrap.el-row {
  margin-left: 15px !important;
}

.night {
  .right {
    background-color: #303445;
    border: 1px solid #2a2d3c;
  }
}
</style>
